/*
 * Copyright 2014 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.yanwq.nwa.im.netty;

import android.util.Log;

import com.yanwq.nwa.im.Connector;
import com.yanwq.nwa.im.MessageMgr;

import java.net.URI;

import javax.net.ssl.SSLEngine;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory;
import io.netty.handler.codec.http.websocketx.WebSocketVersion;
import io.netty.handler.ssl.SslHandler;

public final class WebSocketClientRunner {

    private URI uri;
    private EventLoopGroup group;
    private Bootstrap bootstrap;
    private WebSocketClientHandler handler;
    private Channel channel;

    public WebSocketClientRunner(URI uri) {
        this.uri = uri;
    }

    public void run() throws Exception {
        // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00.
        // If you change it to V00, ping is not supported and remember to change
        // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline.
        group = new NioEventLoopGroup();
        handler = new WebSocketClientHandler(
                WebSocketClientHandshakerFactory.newHandshaker(
                        uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders()));
        bootstrap = new Bootstrap();

        final String protocol = uri.getScheme();
        ChannelInitializer<SocketChannel> initializer;
        // Normal WebSocket
        if ("ws".equals(protocol)) {
            initializer = new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline()
                            .addLast("http-codec", new HttpClientCodec())
                            .addLast("aggregator", new HttpObjectAggregator(8192))
                            .addLast("ws-handler", handler);
                }
            };

            // Secure WebSocket
        } else if ("wss".equals(protocol)) {
            initializer = new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    SSLEngine engine = WebSocketSslClientContextFactory.getContext().createSSLEngine();
                    engine.setUseClientMode(true);

                    ch.pipeline()
                            .addFirst("ssl", new SslHandler(engine))
                            .addLast("http-codec", new HttpClientCodec())
                            .addLast("aggregator", new HttpObjectAggregator(8192))
                            .addLast("ws-handler", handler);
                }
            };
        } else {
            throw new IllegalArgumentException("Unsupported protocol: " + protocol);
        }

        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(initializer);
        channel = bootstrap.connect(uri.getHost(), uri.getPort()).sync().channel();
        handler.handshakeFuture().sync();
        MessageMgr.getInstance().initBlockingMessageQueue(channel);
    }

    public void connect() {
        new Thread(new Runnable() {
            @Override
            synchronized public void run() {
                Connector.getInstance().setStat(Connector.ConnectionStat.CONNECTING);
                try {
                    Log.i("WebSocketClientRunner", "connect");
                    WebSocketClientRunner.this.run();
                } catch (Exception e) {
                    e.printStackTrace();
                    try {
                        Thread.sleep(10 * 1000);
                    } catch (InterruptedException ie) {
                        ie.printStackTrace();
                    }
                    Thread.currentThread().interrupt();
                    Log.i("WebSocketClientRunner", "reconnect");
                    new Thread(this).start();
                }
            }
        }).start();
    }
}
